A Simple Example

A simple example is used to demonstrate the basic procedure. Later, more complex examples show how to handle the esoteric cases. First create a file called (say) x.c with the following contents


/* addfive adds 5 to its argument and returns that */

int
addfive(x)
int x;
{
return(x+5);
}

You have now defined a simple C function addfive that takes a C int and returns a C int. The next step is to compile this file using cc thusly

cc -c x.c
This will result in a file called x.o that contains the compiled function addfive.

The idea is to now define a T function called (say) addfiveto that, when called with a T fixnum, will convert the T fixnum to a C int, pass that int to the C function addfive, obtain the result from that as a C int, convert the result back to a T fixnum and return that as its result. Thus, the T function addfiveto behaves similarly to the C function addfive, takes care of all the conversions between C and T, and calls addfive to actually do the computation.

Create a file called y.t that contains the following


(herald y)



;;; adds 5 to its argument
(define-foreign addfiveto
(addfive (in rep/integer x))
rep/integer)

This defines a T function called addfiveto that corresponds to the C function addfive, takes one argument, which is fixnum and returns a fixnum. Compile this file by starting up a T and running orbit

(comfile y)
After this, you will have the files y.mo, y.mn, and y.mi (y.vo, y.vn, and y.vi on the Vax).

Now, you are all set. In the same (or another) T, you should first load in the compiled C file x.o. This is accomplished by executing the following T function

(load-foreign  "x.o")
The corresponding T function is now loaded in using
(load 'y)
Now, you have the T function addfiveto defined that will do the right thing. Note that the order of the two loads is important. The compiled C function must be loaded in first, before the compiled T function is loaded in. The file containing the define-foreigns (in this case y.t must be compiled. It will not work interpreted.

Try out the new function


(addfiveto 6)

11
(addfiveto 8)
13